<#include '../header.ftl'>
<#include '../showresult/header.ftl'>

    <style>
    /*------公共样式开始------*/

    /* 避免inline里面的字体重叠 */
    .layui-inline .layui-form-label {
        width: auto;
    }

    /* 制作人头像框选中特效 */
    .img-box {
        position: relative;
        overflow: hidden;
    }
    .img-box:after {
        position:absolute;
        left: 0;
        top: 0;
        opacity: 0;
        width:100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.3);
        content: attr(data-text);
        color: #FFF;
        text-align: center;
        padding: 32% 0;
        border-radius: 100%;
        font-style: normal;
        pointer-events: none;
        transition: opacity 0.6s;
        -moz-transition:opacity 0.6s; /* Firefox 4 */
        -webkit-transition:opacity 0.6s; /* Safari and Chrome */
        -o-transition:opacity 0.6s; /* Opera */
    }
    .img-box:hover:after {
        opacity: 1;
    }
    .img-box-before:after {
        /*line-height: 39px;*/
        padding: 12% 0;
    }

    .layui-inline-block {
        display: inline-block !important;
    }

    /* 取消reboot.scss对legend标签的影响 */
    fieldset legend {
        width: auto;
    }

    div.picture_div {
        margin-bottom: 5px;
        margin-right: 5px;
        position: relative;
        display: inline-block;
    }

    .picture_describe {
        color: white;
        cursor: pointer;
        position: absolute;
        top: 80%;
        left: 0;
        text-align: center;
        width: 100%;
        background-color: rgba(0, 0, 0, 0.2);
        line-height: 24px;
        height: 20%;        font-style: normal;
    }

    .picture_div:hover > .picture_close {
        display: inline-block;
    }

    .picture_close {
        display: none;
        position: absolute;
        right: 0;
        font-size: 22px;
        cursor: pointer;
        background-color: rgba(0, 0, 0, 0.2);
    }
    /*------公共样式结束------*/

    /*------小屏幕设备开始------*/
    @media (max-width: 767px) {
        div.picture_div {
            margin-left: 104px;
        }
    }
    /*------小屏幕设备结束------*/

    /*------中大型屏幕设备开始------*/
    @media (min-width: 768px) {
    }
    /*------中大型屏幕设备结束------*/
    </style>

    <main style="min-height: ${maxHeight}px">
        <div style="max-width: ${maxWidth}px;margin: 0 auto">

            <#-- 手动添加成果开始 -->
            <fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
                <legend>添加成果</legend>
            </fieldset>
            <div class="layui-btn-container" style="padding-left: 15px">
                <button type="button" class="layui-btn" id="addResultBtn">开始添加</button>
            </div>
            <#-- 手动添加成果结束 -->

            <#--  成果导入开始  -->
            <fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
                <legend>成果导入</legend>
            </fieldset>
            <div class="layui-btn-container" style="padding-left: 15px">
                <button type="button" class="layui-btn" id="download">下载模板</button>
                <button type="button" class="layui-btn" id="upload">一键导入</button>
                <button type="button" class="layui-btn" id="searchId">查询用户id</button>
            </div>
            <blockquote  style="margin-left: 15px" class="layui-elem-quote">
                请在下载的模板中填入相应的数据，不要修改表的结构！否则无法导入成功！
            </blockquote>
            <#--  成果导入结束  -->

            <#--  成果导出开始  -->
            <fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
                <legend>成果导出</legend>
            </fieldset>
            <div>
                <div class="layui-form">
                    <div class="layui-form-item" style="margin-bottom: 0">
                        <div class="layui-inline">
                            <label class="layui-form-label">时间范围</label>
                            <div class="layui-input-inline">
                                <input type="text" name="time" placeholder="选择时间范围" id="time" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">类型范围</label>
                            <div class="layui-input-inline">
                                <select name="type" lay-verify="required" id="type_view"></select>
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label" style="width: auto;line-height: 35px">查询的人</label>
                        <div class="layui-input-block" style="margin-left: 0;line-height: 39px;max-height: 300px;overflow: auto" id="seach">
                            <button type="button" class="layui-btn addPerson">
                                <i class="layui-icon">&#xe608;</i> 添加
                            </button>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-btn-container" style="padding-left: 15px">
                            <button class="layui-btn" lay-submit lay-filter="export_result">导出</button>
                            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                        </div>
                    </div>
                </div>
            </div>
            <#--  成果导出结束  -->
        </div>
    </main>

    <#-- 添加成果开始 -->
    <script type="text/html" id="addResult">
        <form class="layui-form" action="#" id="addResultForm" style="padding-top: 10px">
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: auto">成果名称</label>
                <div class="layui-input-block">
                    <input type="text" name="name" lay-verify="required"
                           lay-reqtext="成果名称不能为空！"
                           autocomplete="off" placeholder="请输入名称" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: auto">获得时间</label>
                <div class="layui-input-block">
                    <input type="text" name="getTime" class="layui-input" id="getTime">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: auto">成果链接</label>
                <div class="layui-input-block">
                    <input type="text" name="link" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: auto"> 成果类型</label>
                <div class="layui-input-block">
                    <select name="typeId" lay-verify="required">
                        <option value="0">待确定</option>
                        {{# layui.each(d.payload, function(index, item) { }}
                        <option value="{{item.id}}">{{ item.name }}</option>
                        {{# }) }}
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: auto;line-height: 35px">合作人员</label>
                <div class="layui-input-block" style="line-height: 39px;max-height: 300px;overflow: auto" id="seach">
                    <button type="button" class="layui-btn addPersonNoMe">
                        <i class="layui-icon">&#xe608;</i> 添加
                    </button>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: auto">成果简介</label>
                <div class="layui-input-block">
                    <textarea placeholder="请输入成果简介" name="info" class="layui-textarea"></textarea>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: auto">成果图片</label>
                <div class="layui-input-block" id="resultPictures">
                    <div class="layui-upload-drag" id="addResultPicture">
                        <i class="layui-icon layui-icon-picture-fine"></i>
                        <p>点击进行图片上传剪切</p>
                    </div>
                </div>
            </div>
            <div class="layui-form-item" style="padding-left: 2%;">
                <div id="layer-photos-demo">
                </div>
            </div>
            <div class="layui-form-item layui-hide">
                <input type="button" lay-submit lay-filter="result-add-submit" id="resultAddSubmit" value="确认">
            </div>
        </form>
    </script>
    <#-- 添加成果弹窗结束 -->

    <#-- 添加人员弹窗开始 -->
    <script type="text/html" id="addUserForm">
        <form class="layui-form" action="" style="background-color: white;padding-top: 10px">
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: auto">请选择</label>
                <div class="layui-input-block">
                   {{# layui.each(d.payload, function(index, item) { }}
                    <i class="layui-inline layui-inline-block" onmouseover="this.style.cursor='pointer'" style="position: relative">
                        <input type="hidden" name="userId" value="{{ item.id }}" />
                        <div class="img-box" data-text="{{ item.realName }}">
                            {{# if (item.avatarPath != null) { }}
                            <img class="layui-circle layui-anim" src="{{ item.avatarPath }}"
                                 alt="logo" width="50" onclick="chooseThis(this)">
                            {{# } else { }}
                            <img class="layui-circle layui-anim" src="/images/logo.png"
                                 alt="logo" width="50" onclick="chooseThis(this)">
                            {{# } }}
                        </div>
                    </i>
                    {{# }) }}
                </div>
            </div>
        </form>
    </script>
    <#-- 添加人员弹窗结束 -->

    <script type="text/html" id="type">
        <option value="0">待确定</option>
        {{# layui.each(d.payload, function(index, item) { }}
        <option value="{{item.id}}">{{ item.name }}</option>
        {{# }) }}
    </script>

    <script type="text/html" id="users">
        <ul class="list-group">
        {{# layui.each(d, function(index, item) { }}
            <li class="list-group-item layui-row layui-col-space2 ">
                <div class="layui-col-xs3">
                    <i class="layui-inline layui-inline-block" onmouseover="this.style.cursor='pointer'"
                       style="position: relative; cursor: pointer;">
                        <div class="img-box" data-text="{{ item.realName }}">
                            {{# if (item.avatarPath != null) { }}
                            <img class="layui-circle layui-anim" src="{{ item.avatarPath }}"
                                 alt="logo" width="50">
                            {{# } else { }}
                            <img class="layui-circle layui-anim" src="/images/logo.png"
                                 alt="logo" width="50">
                            {{# } }}
                        </div>
                    </i>
                </div>
                <div class="layui-col-xs9">
                    用户Id：{{ item.id }}<br>
                    用户名：{{ item.username }}
                </div>
            </li>
        {{# }) }}
        </ul>
    </script>
    <script>
        function chooseThis(that) {
            if (that.style.borderColor === "") {
                that.style.borderColor = "red";
                that.style.borderStyle = "outset";
                that.style.borderWidth = "2px";
                that.classList.add("layui-anim-scale");
                that.classList.remove("layui-anim-scaleSpring");
            } else {
                that.style.borderColor = "";
                that.style.borderStyle = "";
                that.style.borderWidth = "";
                that.classList.add("layui-anim-scaleSpring");
                that.classList.remove("layui-anim-scale");
            }
        }

        /* 点击已经选择的人员取消选择 */
        $(document).on('click', '.img-box-before', function() {
            $(this).parent().remove()
        });

        $(document).on('click', '#download', function() {
            window.location.href = '/download/demo';
        })


        layui.use(['laydate', 'form', 'layer', 'upload', 'laytpl'], function () {
            const laydate = layui.laydate
                , form = layui.form
                , layer = layui.layer
                , $ = layui.$
                , upload = layui.upload
                , laytpl = layui.laytpl;

            $(document).on('click', '#searchId', function() {
                layer.prompt({
                    title: '查询用户id',
                }, function(value, index, elem){
                    $.get('/user/getId?realName=' + value, function (data) {
                        if (data.success) {
                            layer.close(index);
                            if (data.payload.length > 1) {
                                const getTpl = users.innerHTML
                                laytpl(getTpl).render(data.payload, function(html){
                                    layer.open({
                                        type: 1,
                                        area: ['280px', '50%'],
                                        content: html
                                    });
                                });
                            } else {
                                layer.alert(value + "的id为：" + data.payload[0].id)
                            }
                        } else {
                            layer.msg(data.msg)
                        }
                    })
                });
            })

            $('[data-toggle="tooltip"]').tooltip()

            $.get('/type/get', function(data) {
                const getTpl = type.innerHTML
                    , view = document.getElementById('type_view');
                laytpl(getTpl).render(data, function(html){
                    view.innerHTML = html;
                });
                form.render('select');
            })

            form.on('submit(export_result)', function(data){
                let userIds = [];
                let url = '/excel/export?resultStatus=PASSED';
                $('input[name="userId"]').each(function() {
                    userIds.push($(this).val())
                })
                const time = data.field['time']
                const type = data.field['type']
                if (time != null && "" !== time) {
                    url += "time=" + time + "&"
                }
                if (type != null && "0" !== type) {
                    url += "type=" + type + "&"
                }
                if (userIds.length > 0) {
                    url += "userIds=" + userIds.join();
                }

                window.location.href = url;
                return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
            });

            // 添加成果弹窗
            $('#addResultBtn').click(function () {
                $.get('/type/get', function(data) {
                    const getTpl = addResult.innerHTML
                    laytpl(getTpl).render(data, function(html){
                        layer.open({
                            type: 1,
                            title: '添加成果',
                            area: ['90%', '90%'],
                            content: html,
                            btn: ['确定', '取消'],
                            success: function(index, layero) {
                                form.render();

                                laydate.render({
                                    elem: '#getTime'
                                    , type: 'date'
                                    , value: new Date()
                                    , max: 0
                                })
                            },
                            yes: function(index, layero){
                                let resultAddSubmit = $('#resultAddSubmit');
                                form.on('submit(result-add-submit)', function(data){
                                    let loadIndex  = layer.load(1, {
                                        shade: [0.1, '#fff'] //0.1透明度的白色背景
                                    });
                                    let message = new FormData();
                                    let addMessage = (collection, name) => {
                                        $.each(collection, function (i, value) {
                                            message.append(name, value);
                                        })
                                    }
                                    let addDataField = (names) => {
                                        $.each(names, (i, value) => {
                                            message.append(value, data.field[value])
                                        })
                                    }
                                    let userIds = $("#addResultForm input[name='userId']").map(function () {
                                        return $(this).val();
                                    }).get();
                                    let test = $(".picture_div img").map(function () {
                                        let file = dataURLToFile($(this)[0].src, new Date().getTime());
                                        return file
                                    }).get()
                                    let imgInfos = $(".picture_describe").map(function () {
                                        return $(this).html();
                                    }).get();
                                    if (userIds !== []) {
                                        addMessage(userIds, "userIds")
                                    }
                                    if (test !== []) {
                                        addMessage(test, "imgs")
                                    }
                                    if (imgInfos !== []) {
                                        addMessage(imgInfos, "imgInfos")
                                    }
                                    addDataField(["name", "typeId", "info", "getTime", "link"])

                                    $.ajax({
                                        url: '/result/add',
                                        type: 'post',
                                        contentType: false,
                                        processData: false,
                                        dataType: "json",
                                        data: message,
                                        complete: function () {
                                            layer.close(loadIndex);
                                        },
                                        success: function (data) {
                                            if (data.success) {
                                                layer.closeAll()
                                                layer.msg("添加成功！");
                                            } else {
                                                layer.msg("添加失败！请重试！");
                                            }
                                        },
                                        error: function (data) {
                                            layer.msg("添加失败！请重试！");
                                        }
                                    })
                                    return false; //阻止表单跳转
                                });
                                resultAddSubmit.trigger('click')
                            },
                            btn2: function(index, layero) {
                            }
                        })
                    });
                });
                form.render('select');
            })

            $(document).on('mouseover', '.picture_describe', function () {
                const that = this;
                layer.tips(that.innerHTML, that, {
                    time: 1500
                });
            })

            // 点击修改成果描述
            $(document).on('click', '.picture_describe', function () {
                const that = this;
                layer.prompt({
                    value: this.innerHTML,
                    title: '请输入成果简介',
                }, function(value, index, elem){
                    that.innerHTML = value
                    layer.close(index);
                })
            })

            // 删除点击的成果
            $(document).on('click', '.picture_close', function () {
                const that = this;
                $(that).parent().remove()
            })

            // 成果图片裁剪弹窗
            $(document).on('click', '#addResultPicture', function () {
                layer.open({
                    type: 2,
                    title: '裁切成果图片',
                    content: '/test',
                    area: ['90%', '90%'],
                    success: function(layero, index){
                        var body = layer.getChildFrame('body', index);
                        var w = $(layero).find("iframe")[0].contentWindow;
                        w.myCropper({aspectRatio: 16 / 9}, undefined, $('#layer-photos-demo'), 1)
                        let find = body.find("#check");
                        $(find).on('click', function () {
                            layer.close(layer.index)
                            layer.msg('开始上传...')
                        })
                    }
                })
            })

            // 添人员
            $(document).on('click', '.addPerson', function () {
                const that = this;
                let idInputs = $('.layui-anim-scale').parent().prev().toArray();
                const ids = idInputs.map(t => t.value)
                $.get('/user/others?userIds=' + ids.join(), function(data) {
                    const getTpl = addUserForm.innerHTML;
                    laytpl(getTpl).render(data, function(html){
                        layer.open({
                            type: 1,
                            title: '添加人员',
                            area: '90%',
                            content: html,
                            btn: ['确定', '取消'],
                            yes: function(index, layero){
                                let imgBox = $('.layui-anim-scale').parent();
                                imgBox.addClass("img-box-before")
                                $(that).parent().prepend(imgBox.parent())
                                layer.close(index)
                            },
                            btn2: function(index, layero) {

                            }
                        })
                    })
                })
            });

            // 添人员不包含本人
            $(document).on('click', '.addPersonNoMe', function () {
                const that = this;
                let idInputs = $('.layui-anim-scale').parent().prev().toArray();
                const ids = idInputs.map(t => t.value)
                $.get('/user/others/noMe?userIds=' + ids.join(), function(data) {
                    const getTpl = addUserForm.innerHTML;
                    laytpl(getTpl).render(data, function(html){
                        layer.open({
                            type: 1,
                            title: '添加人员',
                            area: '90%',
                            content: html,
                            btn: ['确定', '取消'],
                            yes: function(index, layero){
                                let imgBox = $('.layui-anim-scale').parent();
                                imgBox.addClass("img-box-before")
                                $(that).parent().prepend(imgBox.parent())
                                layer.close(index)
                            },
                            btn2: function(index, layero) {

                            }
                        })
                    })
                })
            });

            form.render();
            laydate.render({
                elem: '#time'
                , range: true //或 range: '~' 来自定义分割字符
                , max: 0
            })

            upload.render({
                elem: '#upload'
                , url: '/excel/import' //上传接口
                , exts: 'xlsx'
                , accept: 'file'
                ,before: function(){
                    layer.load();
                }
                , done: function(res){
                    layer.closeAll('loading');
                    layer.msg(res.payload)
                }
                , error: function(){
                    layer.msg('上传失败！')
                }
            });

            //将base64转换为blob
            function dataURLToFile(dataUrl, fileName) {
                let arr = dataUrl.split(','), mime = arr[0].match(/:(.*?);/)[1],
                    bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
                while (n--) {
                    u8arr[n] = bstr.charCodeAt(n);
                }
                return new File([u8arr], fileName, {type: mime});
            }
        })
    </script>
<#include '../footer.ftl'>